<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use app\home\model\dealer\Dealer;
use app\home\model\report\ReportGoods;
use OSS\Core\OssException;
use OSS\OssClient;
/**应用公共文件
 * @param $str
 * @return string
 */
function makePwd($str)
{
    $salt = config('salt');
    return md5($str . $salt);
}
/**
 * @param $length
 * @return string
 */
function getRandChar($length)
{
    $str = 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm';

    $string = '';
    for ($i = 0; $i < $length; $i++) {
        $string .= $str[rand(0, strlen($str) - 1)];
    }

    return $string;
}

function dealerMsg($type,$money,$tel=null){
    switch ($type){
        case 1:   //  首单任务
            $res = '恭喜您完成首单任务，获得'.$money.'元奖励，已存入您的账户中';
            break;
        case 2:    //冲刺任务
            $res = '恭喜您完成冲刺任务，获得'.$money.'元奖励，已存入您的账户中';
            break;
    }
    return $res;
}

/**手机号身份证号自动加解密算法
 * @param $num_old
 * @return string
 */
function num_secret($num_old){
    $type=substr($num_old,0,1);//首字符类型
    $ad_mun=10000257;//最小被减数

    if(substr($num_old,-1)=='X' || substr($num_old,-1)=='x'){
        $x=1;//含有X
        $num=substr($num_old,0,-1);//含有X的仅前面的字符参与计算
    }else{
        $x=0;//不含有X
        $num=$num_old;
    }

    $num_len=strlen($num);//号码位数
    $ge=array(
        'Z'  => 0,
        'R'  => 1,
        'E'  => 2,
        'D'  => 3,
        'G'  => 4,
        'Y'  => 5,
        'O'  => 6,
        'P'  => 7,
        'L'  => 8,
        'M'  => 9,
    );

    if(is_numeric($type)){
        //加密
        $q=substr($num,0,8);//前4位
        $q_ad=sprintf("%08d",(intval($q)-intval($ad_mun)));//（前4-x）*2
        $new=$q_ad.substr($num,8);//新的计算号码

        $str='';
        for($i=0;$i<$num_len;$i++){
            $a=substr($new,$i,1);
            foreach($ge as $k=>$v){
                if($v==$a){
                    $str.=$k;
                }

            }
            unset($a);
        }

        if($x) $str.='X';

        return $str;

    }else{
        //解密
        $new='';
        for($i=0;$i<$num_len;$i++){
            $a=substr($num,$i,1);
            foreach($ge as $k=>$v){
                if($a==$k){
                    $new.=$v;
                }
            }
            unset($a);
        }

        $q=substr($new,0,8);//前4位


        $q_ad=sprintf("%08d",intval($q)+intval($ad_mun));//

        $old=$q_ad.substr($new,8);
        if($x) $old.='X';
        return $old;
    }

}
/**手机号加*号处理
 * @param $phone
 * @return mixed
 */
function tel_deal($number,$type=1){
    if($type==1){
        $result = substr_replace($number,"****",3,4);
    }else{ //身份证加*号处理
        $result = substr_replace($number,"****",4,10);
    }

    return $result;
}
/**生成邀请码
 * @param $length
 * @return mixed|string
 */
function randomString($length){
    $ser='ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $str='';
    for($i = 0 ; $i < $length ; $i++){
        $k=rand(0,strlen($ser));
        if($k == strlen($ser)){
            $k=$k-1;
        }
        $str.= $ser[$k];
    }
    return  !empty(Dealer::getFieldVal('dealer_code',$str,'u_id')) ? randomString(8) : $str;
}
/**生成邀请码
 * @param $length
 * @return mixed|string
 */
function randomUrlString($length){
    $ser='ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $str='';
    for($i = 0 ; $i < $length ; $i++){
        $k=rand(0,strlen($ser));
        if($k == strlen($ser)){
            $k=$k-1;
        }
        $str.= $ser[$k];
    }
    return  !empty(ReportGoods::getFieldVal('goods_code',$str,'report_goods_id')) ? randomUrlString(10) : $str;
}

/**阿里云上传
 * @param $fileName
 * @param $saveName
 * @param $tempPath
 * @return mixed
 */
function aliyun($fileName, $saveName, $tempPath)
{
    Vendor('aliyun-oss.autoload');
    $accessKeyId = config('set.OSS_KEYID');
    $accessKeySecret = config('set.OSS_SECRET');
    // Endpoint以杭州为例，其它Region请按实际情况填写。
    $endpoint = config('set.OSS_ENDPOINT');
    // 存储空间名称
    $bucket = config('set.OSS_BUCKET');
    // 文件名称
    $object = $fileName . "/" . $saveName;

    // 由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt
    $filePath = $tempPath;
    try {
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $ossClient->uploadFile($bucket, $object, $filePath);
        $data['status'] = true;
        $data['url'] = config('set.OSS_FILE_PATH') . '/' . $object;

    } catch (OssException $e) {

        $data['status'] = false;
    }
    return $data;
}
/**时间
 * @return false|string
 */
function date_time(){
    return date('Y-m-d H:i:s',time());
}
/**
 * @param $url
 * @param $postFields
 * @return mixed
 */
function postSms($url,$postFields){
    $postFields = http_build_query($postFields);
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_HEADER, 0 );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_URL, $url);
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postFields );
    $result = curl_exec ( $ch );
    curl_close ( $ch );
    return $result;
}
/**id 编译
 * @param id 编译
 * @param [type]  $num [description]
 * @param integer $st  [description] 1加，2解
 */
function reversal($num,$st=1){
    $arr=array(
        'f'	=> 0,
        'r'	=> 1,
        's'	=> 2,
        'a' => 3,
        'y' => 4,
        'h' => 5,
        'g' => 6,
        'q'	=> 7,
        'z' => 8,
        't' => 9,
    );
    $len=strlen($num);
    $str='';
    for($i=0;$i<$len;$i++){
        $a=substr($num,$i,1);
        foreach($arr as $k=>$v){
            if($st == 1 && $a == $v) {
                $str.= $k;
                break;
            }
            if($st == 2 && $a == $k){
                $str.=$v;
                break;
            }
        }
        unset($a);
    }
    return $str;
}

/**生成订单号
 * @param int $lenth
 * @param string $report_code
 * @return string
 */
function getCodeOrder($lenth=14,$report_code=''){
   return $report_code.substr(md5(getRandChar($lenth).time()),0,$lenth-strlen($report_code));//生成订单号
}

/**蘑菇分数 函数
 * @param $sc
 * @return string
 */
function scoreDes($sc){
    if(0<=$sc && $sc<=25) $des='优秀';
    if(26<=$sc && $sc<=45) $des='良好';
    if(46<=$sc && $sc<=65) $des='一般';
    if(66<=$sc && $sc<=85) $des='需重视';
    if(86<=$sc && $sc<=100) $des='急需优化';

    return $des;
}
/**各类分数转100分制
 * @param $min
 * @param $max
 * @param $sc
 * @return float|int
 */
function scoreConversion($min,$max,$sc){
    $max=$max-$min;
    $bei=$max/100;
    $q=floor(($sc-$min)/$bei);

    if($q<0) $q=0;
    if($q>100) $q=100;

    return $q;
}

/**加载指定文件
 * @param string $pash
 * @return mixed
 */
function loadSpecifiedFile($pash='./public'){
   $result= \think\__require_file($pash);
   if(!$result){
       $result=\think\__include_file($pash);
   }
    if(!$result){
        $result=include_once($pash);
    }
    if(!$result){
        $result=include($pash);
    }
        return $result;
}

/**读取json数据
 * @param string $pash
 * @return bool|string
 */
function readJson($pash='./public/'){
    if(empty($pash)){
        return '';
    }
    if(!is_file('./public/'.$pash)){
        return '';
    }
    return  file_get_contents('./public/'.$pash);
}
/**
 * @param $idstr
 * @return mixed|string
 */
 function cardAddress($idstr){
    $id_code=substr($idstr,0,4);
    $id_zone_code_str=readJson('api/report/locale.json');
    $dizhi=@str_replace($id_code,'',substr(strstr($id_zone_code_str,$id_code),0,16));
    if($dizhi){
        return $dizhi;
    }else{
        return '未知';
    }
}

/**获取指定时间多少天后的时间
 * @param string $strTime
 * @param string $day [1 day,-1 day]
 * @return false|string
 */
function getForwardDate($strTime='',$day=''){
     if(!$strTime){
         $strTime=date_time();
     }
    return date('Y-m-d H:i:s',strtotime($day,strtotime($strTime)));
}

/**通过身份证获取出生日期
 * @param string $idCard
 * @return false|string
 */
function getBirthday($idCard=''){
   return date("Y-m-d",strtotime(substr(substr($idCard,6),0,-4)));
}
/**通过生日计算年龄
 * @param $birthday
 * @return bool|false|int
 */
function getAge($birthday){
    $age = strtotime($birthday);
    if($age === false){
        return false;
    }
    list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age));
    $now = strtotime("now");
    list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now));
    $age = $y2 - $y1;
    if((int)($m2.$d2) < (int)($m1.$d1))
        $age -= 1;
    return $age;
}

/**获取到当前域名类型
 * @return string
 */
function get_http_type()
{
    $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
    return $http_type;
}

/**获取支付方式
 * @param $type
 * @return string
 */
function getPayType($type){
    switch($type) {
        case 1:
            return 'alipay';
            break;
        case 2:
            return 'wxpay';
            break;
        case 3:
            return 'wxh5';
            break;
        case 4:
            return '';
            break;
        case 5:
            return 'alipayAPP';
            break;
    }
}

/**订单列表是否已经查看列表
 * @param $dealerId     代理id
 * @param $see          默认0未读 1 已读
 * @param $type         0=全部 1 查询成功列表 2 查询失败列表 3 未支付列表 4已退款列表
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function msgOrderSee($dealerId,$see,$type){
    $where=[
        "dealer_id"=>$dealerId,
        "type"=>$type
    ];
    $see=[
        "dealer_id"=>$dealerId,
        "see"=>$see,
        "type"=>$type,
    ];
    if(db("msg_order_see")->where($where)->count('id') > 0){
        db("msg_order_see")->where($where)->update($see);
    }else{
        db("msg_order_see")->insert($see);
    };

}
/**统计订单
 * @param $field  统计的字段
 * @param $report_code  报告编码
 * @param int $val  增加的值
 * @param string $date  时间
 * @throws \think\Exception
 */
function setStcOrder($field,$report_code,$val=1,$date=''){
    if(empty($date)){
        $date=date("Y-m-d",time());
    }
    $where['date_day']   =$date;
    $where['report_code']=$report_code;
    $rc=db("statistics_order")->where($where)->count();
    if($rc > 0){
        db("statistics_order")->where($where)->setInc($field,$val);
    }else{
        $data[$field]       =$val;
        $data['report_code']=$report_code;
        $data['date_day']   =$date;
        $data['date_month'] =date("Y-m",strtotime($date));
        db("statistics_order")->insert($data);
    }
    return true;
}

/**统计流量
 * @param $field        统计字段
 * @param int $val      增加的值
 * @param string $date  时间
 * @throws \think\Exception
 */
function setStcFlow($field,$val=1,$date=''){
    if(empty($date)){
        $date=date("Y-m-d",time());
    }
    $where['date_day']   =$date;
    $rc=db("statistics_flow")->where($where)->count();
    if($rc > 0){
        db("statistics_flow")->where($where)->setInc($field,$val);
    }else{
        $data[$field]       =$val;
        $data['date_day']   =$date;
        $data['date_month'] =date("Y-m",strtotime($date));
        db("statistics_flow")->insert($data);
    }
    return true;
}

/**代理相关统计
 * @param $field        统计的字段
 * @param int $val      增加的值
 * @param string $date  时间
 * @throws \think\Exception
 */
function setStcDealer($field,$val=1,$date=''){
    if(empty($date)){
        $date=date("Y-m-d",time());
    }

    $where['date_day']   =$date;
    $rc=db("statistics_dealer")->where($where)->count();
    if($rc > 0){
        db("statistics_dealer")->where($where)->setInc($field,$val);
    }else{
        $data[$field]       =$val;
        $data['date_day']   =$date;
        $data['date_month'] =date("Y-m",strtotime($date));
        db("statistics_dealer")->insert($data);
    }
    if($field == "register"){//如果是注册
        if($rc > 0){//如果有数据就加1
            db("statistics_dealer")->where($where)->setInc('register_total',$val);
        }else{//如果没有数据就查找上一天
            $rel =db("statistics_dealer")
                ->where(['date_day'=>date('Y-m-d',strtotime('-1 day',strtotime($date)))])
                ->find();
                $data=[];
            if($rel){
                $data['register_total'] =$rel['register_total']+$val;//累计注册
            }else{
                $num=db("dealer")->field('dealer_id')->count();
                $data['register_total'] =$num+$val;
            }
            db("statistics_dealer")->where($where)->update($data);
        }
    }
    return true;
}

//最新格子衫短信接口
/*
*templateId    1.TTEMsgCode:您的{XX}验证码为：{XX}（若非本人操作，请忽略，5分钟之内有效）
*              2.TTERepError:很抱歉！由于系统原因您刚刚查询的信用测评获取异常，系统已发起退款至支付账户，请注意查收{XX=。}
*              3.TTERefund:您申请的退款，系统已发起退款至支付账户，请注意查收{XX=。}
*              4.TTEUpdate:恭喜您，升级为{XX}合伙人，有效期至{XX}。
*              5.TTEExtend:恭喜您，{XX}合伙人有效期延长至{XX}。
*              6.TTEExpire:您的{XX}合伙人身份将于{XX}到期，为了保障您的{XX}权力，可前往App进行升级操作。
*phoneNum      手机号
*params        多个参数依次逗号隔开，例子：'蘑菇,123456'
*/
function smsComA($templateId,$phoneNum,$params){

    $url='http://36api.com/Gezshan/SmsCom/send';
    $time=time();
    $data=[
        'appCode' =>config('inside.appCode'),
        'appSign' =>md5(config('inside.appCode').config('inside.appKey').$time),
        'time'=>$time,
        'templateId'=>$templateId,
        'phoneNum'=>$phoneNum,
        'params'=>$params,
    ];
    $re=postSms($url,$data);
    $re=json_decode($re,true);
    return $re;
}



